<template>
  <el-dialog :model-value="dialogVisible" :title="state.title" width="35%" align-center @closed="handleCancel">
    <el-form ref="refForm" :model="form.data" :rules="form.rules" label-position="right">
      <el-form-item prop="roleCode" label="角色编号">
        <el-input v-model="form.data.roleCode" placeholder="请输入编号"></el-input>
      </el-form-item>
      <el-form-item prop="roleName" label="角色名称">
        <el-input v-model="form.data.roleName" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item prop="roleStatus" label="角色状态">
        <el-radio-group v-model="form.data.roleStatus">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { withDefaults, computed, reactive, ref, nextTick } from 'vue'
import { ElDialog, ElMessage, ElForm, ElFormItem, ElInput, ElRadioGroup, ElRadio } from 'element-plus'
import { util } from '@/utils'
import { roleApi } from '@/api/modules/system/role'
import type { Role } from '@/api/modules/system/role'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['success', 'update:visible'])

const dialogVisible = computed(() => props.visible)

const refForm = ref()
const form = reactive<{ data: Role; rules: any }>({
  data: { roleStatus: 1 } as Role,
  rules: {
    roleCode: [{ required: true, message: '请输入编号' }],
    roleName: [{ required: true, message: '请输入名称' }]
  }
})

const state = computed(() => {
  if (form.data.roleId) {
    return { isCreate: false, title: '修改角色' }
  } else {
    return { isCreate: true, title: '新建角色' }
  }
})

const handleSave = () => {
  refForm.value.validate((valid: boolean) => {
    if (valid) {
      saveCallback(roleApi.save(form.data))
    }
  })
}
const saveCallback = (promise: Promise<AxiosType.Response>) => {
  promise.then(resp => {
    if (resp.success) {
      ElMessage.success(`已${state.value.title} [ ${form.data.roleName} ]`)
      emits('success')
      handleCancel()
    } else {
      ElMessage.error(resp.message)
    }
  })
}

const handleCancel = () => {
  form.data = { roleStatus: 1 } as Role
  refForm.value.resetFields()
  emits('update:visible', false)
}

const setFormData = (data: Role) => {
  nextTick(() => (form.data = util.cloneObject(data)))
}
defineExpose({ setFormData })
</script>

<style lang="scss" scoped></style>
